<template>
  <div class="search-container">
    <form action="/" class="search-form">
      <van-search
        class="search-nav"
        v-model="searchText"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        @focus="isResultShow = false"
        show-action
      />
      </form>
      <SearchResult
        v-if="isResultShow"
        :searchText="searchText"
      />
      <SearchSuggestion
        v-else-if="searchText"
        :searchText="searchText"
        @search="onSearch"
      />
      <SearchHistory
        v-else
        :searchHistories="searchHistories"
        @deleteAllHistories="deleteAllHistories"
        @deleteSingleHistory="deleteSingleHistory"
      />
  </div>
</template>

<script>
import SearchHistory from './components/search-history'
import SearchSuggestion from './components/search-suggestion'
import SearchResult from './components/search-result'
import { setItem, getItem } from '@/utils/storage'
export default {
  name: 'SearchIndex',
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  data () {
    return {
      searchText: '',
      isResultShow: false,
      searchHistories: JSON.parse(getItem('SEARCH_HISTORIES')) || [] // 历史记录
    }
  },
  watch: {
    searchHistories: {
      handler () {
        setItem('SEARCH_HISTORIES', this.searchHistories)
      }
    }
  },
  methods: {
    onSearch (val) {
      if (val) {
        this.searchText = val
        // 历史记录中：1.不能重复 2.新添加的要在最上面
        const i = this.searchHistories.indexOf(val)
        if (i === -1) { // 不包含则添加进数组
          this.searchHistories.unshift(val)
        } else { // 包含则先删除原来的，再把这个新的添加到头上
          this.searchHistories.splice(i, 1)
          this.searchHistories.unshift(val)
        }
        this.isResultShow = true // 显示搜索结果
      } else {
        this.$toast('搜索内容不能为空！')
      }
    },
    onCancel () {
      this.$router.back()
    },
    deleteAllHistories () {
      this.searchHistories = []
    },
    deleteSingleHistory (index) {
      this.searchHistories.splice(index, 1)
    }
  }
}
</script>

<style scoped lang="less">
  .search-container {
    padding-top: 110px;
    .search-form {
      position: fixed;
      top: 0;
      left: 0;
      right: 0;
      z-index: 1;
    }
    .search-nav {
      height: 100%;
      background-color: #3296fa;
      .van-search__content {
        border-radius: 10px;
      }
      .van-search__action {
        color: #fff;
      }
    }
  }
</style>
